<?php
/**
 * Created by gumaor.com
 * User: tommy
 */

namespace lib\jwt;


use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;

class Token
{
    const SALT = 'Cbv0nshEcaC1C2nnBz85';
    const JTI = 'w30l48Ev9z23Bzi91gB0';

    /**
     * 创建Token
     *
     * @param  string $uid 需要保存的用户身份标识
     * @return String
     **/
    public static function createToken($uid = null)
    {
        $signer = new Sha256();
        $token = (new Builder())->setIssuer('http://api.timophp.com')
            ->setAudience('http://api.timophp.com')
            ->setId(self::JTI, true) //自定义标识
            ->setIssuedAt(time()) //当前时间
            ->setExpiration(time() + 86400) //token有效期时长
            ->set('uid', $uid)
            ->sign($signer, self::SALT)
            ->getToken();
        return (String) $token;
    }

    /**
     * 检测Token是否过期与篡改
     *
     * @param string token
     * @return boolean
     **/
    public static function validateToken($token = null)
    {
        $token = (new Parser())->parse((String) $token);
        $signer = new Sha256();
        if (!$token->verify($signer, self::SALT)) {
            return false; //签名不正确
        }

        $validationData = new ValidationData();
        $validationData->setIssuer('http://api.timophp.com');
        $validationData->setAudience('http://api.timophp.com');
        $validationData->setId(self::JTI);//自字义标识

        if (!$token->validate($validationData)) {
            return false;
        }

        return $token->getClaim('uid');
    }
}
